from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager


class UserManager(BaseUserManager):
    """自定义用户管理器"""
    
    def create_user(self, phone, password=None, **extra_fields):
        """创建普通用户"""
        if not phone:
            raise ValueError('用户必须有手机号')
        user = self.model(phone=phone, **extra_fields)
        if password:
            user.set_password(password)
        user.save(using=self._db)
        return user
    
    def create_superuser(self, phone, password=None, **extra_fields):
        """创建超级用户"""
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        
        if extra_fields.get('is_staff') is not True:
            raise ValueError('超级用户必须有is_staff=True')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('超级用户必须有is_superuser=True')
        
        return self.create_user(phone, password, **extra_fields)


class User(AbstractUser):
    """用户模型"""
    
    # 用户角色选项
    class Role(models.TextChoices):
        SHIPPER = 'shipper', '货主'
        DRIVER = 'driver', '车主'
        ADMIN = 'admin', '管理员'
    
    # 解决与内置 auth.User 模型的反向关系冲突
    groups = models.ManyToManyField(
        'auth.Group',
        verbose_name='groups',
        blank=True,
        help_text='The groups this user belongs to.',
        related_name='user_app_user_set',
        related_query_name='user_app_user'
    )
    user_permissions = models.ManyToManyField(
        'auth.Permission',
        verbose_name='user permissions',
        blank=True,
        help_text='Specific permissions for this user.',
        related_name='user_app_user_set',
        related_query_name='user_app_user'
    )
    
    # 基本信息
    username = models.CharField(max_length=150, blank=True, null=True)  # 不使用username作为登录凭证
    phone = models.CharField(max_length=11, unique=True, verbose_name='手机号')
    openid = models.CharField(max_length=64, unique=True, null=True, blank=True, verbose_name='微信OpenID')
    role = models.CharField(max_length=10, choices=Role.choices, default=Role.SHIPPER, verbose_name='用户角色')
    avatar = models.URLField(max_length=255, null=True, blank=True, verbose_name='头像URL')
    
    # 认证状态字段
    role_authstatus = models.BooleanField(default=False, verbose_name='角色认证状态',
                                         help_text='用户角色的认证状态，True表示已通过认证，False表示未通过认证')
    
    # 企业信息
    company = models.CharField(max_length=100, null=True, blank=True, verbose_name='公司名称',
                              help_text='用户所属的公司名称')
    credit_score = models.DecimalField(max_digits=3, decimal_places=1, default=5.0, verbose_name='信用评分',
                                      help_text='用户信用评分，范围0.0-5.0')
    
    # JWT令牌存储
    access_token = models.TextField(null=True, blank=True, verbose_name='访问令牌',
                                   help_text='当前有效的JWT访问令牌，用于API接口认证')
    refresh_token = models.TextField(null=True, blank=True, verbose_name='刷新令牌',
                                    help_text='JWT刷新令牌，用于获取新的访问令牌')
    
    # 位置信息
    longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True, verbose_name='经度')
    latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True, verbose_name='纬度')
    
    # 设置手机号为用户名
    USERNAME_FIELD = 'phone'
    REQUIRED_FIELDS = []
    
    objects = UserManager()
    
    class Meta:
        verbose_name = '用户'
        verbose_name_plural = '用户'
        ordering = ['-date_joined']
    
    def __str__(self):
        return f"{self.phone} ({self.get_role_display()})"


class UserProfile(models.Model):
    """用户详细资料"""
    
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile', verbose_name='用户')
    real_name = models.CharField(max_length=50, null=True, blank=True, verbose_name='真实姓名')
    id_card = models.CharField(max_length=18, null=True, blank=True, verbose_name='身份证号')
    address = models.CharField(max_length=255, null=True, blank=True, verbose_name='地址')
    
    # 身份证照片
    id_card_front_image = models.URLField(max_length=255, null=True, blank=True, verbose_name='身份证照片（正面）')
    
    # 车主特有信息
    driver_license = models.CharField(max_length=50, null=True, blank=True, verbose_name='驾驶证号')
    driver_license_image = models.URLField(max_length=255, null=True, blank=True, verbose_name='驾驶证照片URL')
    
    # 企业特有信息
    business_license = models.CharField(max_length=50, null=True, blank=True, verbose_name='营业执照号')
    business_license_image = models.URLField(max_length=255, null=True, blank=True, verbose_name='营业执照照片URL')
    
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '用户详细资料'
        verbose_name_plural = '用户详细资料'
    
    def __str__(self):
        return f"{self.user.phone}的详细资料"